package com.aaa.config;


import com.aaa.filter.CaptchaFilter;
import com.aaa.util.DefaultMsg;
import com.google.gson.Gson;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * oauth2.0 资源配置
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResConfig extends ResourceServerConfigurerAdapter {

    @Resource
    CaptchaFilter captchaFilter;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // //captcha请求不进行拦截
//                "/oauth/token"不拦截
                .antMatchers("/sendMail","/addLeadingUsers","/checkUsername").permitAll().anyRequest().authenticated()
                .and().addFilterBefore(new CaptchaFilter(), UsernamePasswordAuthenticationFilter.class)
                //登录访问路径
                //配置如果没有登录 返回json数据 而不是跳转到登录界面
                .exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        DefaultMsg defaultMsg = new DefaultMsg();
                        //设置没有登录的状态码
                        defaultMsg.setCode(403);
                        defaultMsg.setSuccess(0);
                        defaultMsg.setMsg("用户没有登录");
                        response.setCharacterEncoding("UTF-8");
                        response.setHeader("Content-Type", "text/html;charset=UTF-8");
                        //把defaultMsg对象转换成json字符串
                        String json = new Gson().toJson(defaultMsg);
                        PrintWriter writer = response.getWriter();
                        writer.print(json);
                        writer.close();
                    }
                })
                //如果用户没有权限 不返回403状态码 返回自定义的json数据
                .and().exceptionHandling().accessDeniedHandler(new AccessDeniedHandler(){
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        DefaultMsg defaultMsg = new DefaultMsg();
                        defaultMsg.setCode(401);
                        defaultMsg.setSuccess(0);
                        defaultMsg.setMsg("没有权限,滚吧");
                        response.setCharacterEncoding("UTF-8");
                        response.setHeader("Content-Type","text/html;charset=UTF-8");
                        //把defaultMsg对象转换成json字符串
                        String json = new Gson().toJson(defaultMsg);
                        PrintWriter writer = response.getWriter();
                        writer.print(json);
                        writer.close();
                    }
                })
                //禁用CSRF
                .and().csrf().disable()
                //session改成无状态的
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}


